package org.jeecg.modules.incomingRecord.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.incomingRecord.entity.IncomingRecord;
import org.jeecg.modules.incomingRecord.service.IIncomingRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.inventory.entity.Inventory;
import org.jeecg.modules.inventory.service.IInventoryService;
import org.jeecg.modules.inventoryDetail.entity.InventoryDetail;
import org.jeecg.modules.inventoryDetail.service.IInventoryDetailService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 入库信息表
 * @Author: jeecg-boot
 * @Date:   2025-04-15
 * @Version: V1.0
 */
@Api(tags="入库信息表")
@RestController
@RequestMapping("/incomingRecord/incomingRecord")
@Slf4j
public class IncomingRecordController extends JeecgController<IncomingRecord, IIncomingRecordService> {
	@Autowired
	private IIncomingRecordService incomingRecordService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IInventoryDetailService inventoryDetailService;
	
	/**
	 * 分页列表查询
	 *
	 * @param incomingRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "入库信息表-分页列表查询")
	@ApiOperation(value="入库信息表-分页列表查询", notes="入库信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(IncomingRecord incomingRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<IncomingRecord> queryWrapper = QueryGenerator.initQueryWrapper(incomingRecord, req.getParameterMap());
		Page<IncomingRecord> page = new Page<IncomingRecord>(pageNo, pageSize);
		IPage<IncomingRecord> pageList = incomingRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param incomingRecord
	 * @return
	 */
	@AutoLog(value = "入库信息表-添加")
	@ApiOperation(value="入库信息表-添加", notes="入库信息表-添加")
	@PostMapping(value = "/add")
	@Transactional(rollbackFor = Exception.class)
	public Result<?> add(@Valid @RequestBody IncomingRecord incomingRecord) {
		Integer materialType = incomingRecord.getMaterialType();
		String batchId = incomingRecord.getBatchId();

		if (StringUtils.isEmpty(batchId)) {
			return Result.error("批次号不能为空");
		}

		if (1 == materialType) {//原料
			Inventory existingInventory = inventoryService.getByBatchId(batchId);
			if (existingInventory == null) {
				Inventory newInventory = createInventory(incomingRecord);
				inventoryService.save(newInventory);

				createInventoryDetail(newInventory.getId(), batchId, materialType, incomingRecord.getEntryTime(), incomingRecord.getQuantity());
			} else {
				existingInventory.setCurrentQuantity(
						existingInventory.getCurrentQuantity().add(incomingRecord.getQuantity())
				);
				inventoryService.updateById(existingInventory);

				createInventoryDetail(existingInventory.getId(), batchId, materialType, incomingRecord.getEntryTime(), incomingRecord.getQuantity());
			}
		} else {
			if (inventoryService.existsByBatchId(batchId)) {
				return Result.error("非原料类型批次号必须唯一");
			}
			Inventory newInventory = createInventory(incomingRecord);
			inventoryService.save(newInventory);
		}

		incomingRecordService.save(incomingRecord);
		return Result.OK("添加成功！");
	}

	 private Inventory createInventory(IncomingRecord record) {
		 return new Inventory()
				 .setMaterialId(record.getMaterialId())
				 .setBatchId(record.getBatchId())
				 .setTankId(record.getTankId())
				 .setMaterialType(record.getMaterialType())
				 .setCurrentQuantity(record.getQuantity())
				 .setEntryTime(record.getEntryTime())
				 .setStartTime(record.getStartTime())
				 .setEndTime(record.getEndTime())
				 .setStatus(1);
	 }

	 private void createInventoryDetail(String inventoryId, String batchId,
										Integer materialType, Date entryTime, BigDecimal quantity) {
		 InventoryDetail detail = new InventoryDetail()
				 .setInventoryId(inventoryId)
				 .setBatchId(batchId)
				 .setMaterialType(materialType)
				 .setCurrentQuantity(quantity)
				 .setEntryTime(entryTime);
		 inventoryDetailService.save(detail);
	 }
	
	/**
	 *  编辑
	 *
	 * @param incomingRecord
	 * @return
	 */
	@AutoLog(value = "入库信息表-编辑")
	@ApiOperation(value="入库信息表-编辑", notes="入库信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody IncomingRecord incomingRecord) {
		incomingRecordService.updateById(incomingRecord);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "入库信息表-通过id删除")
	@ApiOperation(value="入库信息表-通过id删除", notes="入库信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		incomingRecordService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "入库信息表-批量删除")
	@ApiOperation(value="入库信息表-批量删除", notes="入库信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.incomingRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "入库信息表-通过id查询")
	@ApiOperation(value="入库信息表-通过id查询", notes="入库信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		IncomingRecord incomingRecord = incomingRecordService.getById(id);
		if(incomingRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(incomingRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param incomingRecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, IncomingRecord incomingRecord) {
        return super.exportXls(request, incomingRecord, IncomingRecord.class, "入库信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, IncomingRecord.class);
    }

}
